import path from "path";
import chalk from "chalk";
import fs from "fs";
import inquirer from "inquirer";
import { RFile, Openapi2ToOpenapi3 } from "../util.js";
import F2S from "../js/F2S.js";
import request from "request";
// const yaml = require('js-yaml');
/**
 * 输出文件
 *
 * @param {String} filePath
 * @param {String} content
 */
const WriteFile = (filePath, content) => {
  fs.writeFile(path.resolve(filePath), content, "utf8", function (err) {
    if (err) {
      console.log(chalk.red(err));
    } else {
      console.log(chalk.greenBright(filePath + " : 输出成功!"));
    }
  });
};

/**
 * 导出文件
 *
 * @param {*} options
 * @param {*} config
 * @param {*} TypeStr
 * @param {*} ignore
 */
const ExportsFile = async (File, FileName, config, OutPut) => {
  WriteFile(OutPut + "/" + FileName + ".js", F2S(File, config, FileName));
};

// const Config = {
//   // 使用新版 EventName 格式化方法
//   NewNameRule: true,
//   // 用于去掉重复的 Path 字段
//   IgnorePath: ["default"],
//   // swagger 文档地址
//   path: [
//     {
//       fileName: "CommonApi",
//       linkName: "默认链接",
//       url: "http://192.168.11.118:8880/openapi.yaml",
//     },
//   ],
//   // 接口文件输出地址
//   apiPath: "api",
//   // 文档输出附加模块(头部模块)
//   formatModuleString: `// 经过封装的请求方法地址
// import request from '@/libs/request.js';`,
// };

const Questions = async (config) => {
  //   list.unshift("全部");

  var list = ["全部"];

  for (let i = 0; i < config.length; i++) {
    const element = config[i];
    list.push(element.linkName);
  }

  const questions = [
    {
      type: "list",
      name: "_index",
      message: "请选择需要更新的模块",
      choices: list,
      filter: (val) => list.indexOf(val),
    },
  ];
  var answers = await inquirer.prompt(questions);
  if (answers._index == 0) {
    return null;
  } else {
    return config[answers._index - 1];
  }
};

export const Run = async (config) => {
  var requestList = [];
  var ans = await Questions(config.path);
  if (!ans) {
    config.path.forEach((ele) => {
      requestList.push(RFile(ele.url));
    });
    var allDoc = await Promise.all(requestList);
    allDoc.forEach(async (ele, index) => {
      var FileObject = config.path[index];
      var JsonDataV3 = await Openapi2ToOpenapi3(ele);
      ExportsFile(JsonDataV3, FileObject.fileName, config, config.apiPath);
    });
  } else {
    var JsonData = await RFile(ans.url);
    var JsonDataV3 = await Openapi2ToOpenapi3(JsonData);
    ExportsFile(JsonDataV3, ans.fileName, config, config.apiPath);
  }
};
